package com.hq.door.controller;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hq.door.bean.OAuth;
import com.hq.door.dto.DClass;
import com.hq.door.dto.ImageCode;
import com.hq.door.dto.OutrequestInfo;
import com.hq.door.dto.Pagination;
import com.hq.door.dto.Parent;
import com.hq.door.dto.ParentApplyFront;
import com.hq.door.dto.ParentRecordFront;
import com.hq.door.dto.StudentInfo;
import com.hq.door.dto.TeacherDto;
import com.hq.door.pojo.TParent;
import com.hq.door.pojo.TStudent;
import com.hq.door.pojo.TTeacher;
import com.hq.door.service.IParentService;
import com.hq.door.service.TTeacherService;
import com.hq.door.util.HttpClientUtil;
import com.hq.door.util.JacksonUtil;
import com.hq.door.util.staticErrorCode;

@Controller
@RequestMapping("/front/teacher")
@CrossOrigin(origins = { "*" }, allowedHeaders = { "Access-Control" })
public class TeacherFrontController {
	@Autowired
	TTeacherService teacherService;

	// ------------------------------------------------------------------------------------
	/**
	 * 分页带参查询老师对应的学生刷卡记录信息
	 * 
	 * @param pib
	 * @return
	 */
	@RequestMapping(value = "/record")
	@ResponseBody
	public Pagination findStuInfosByRecord(HttpSession session,
			ParentRecordFront prf) {
		System.out.println(prf);
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		Pagination pagination = teacherService.queryRecordsByTeacher(tTeacher,
				prf);
//		if (pagination == null) {
//			pagination = new Pagination(0, "", null);
//		}
		return pagination;
	}

	/**
	 * 分页带参查询所有学生外出申请记录信息
	 * 
	 * @param pib
	 * @return
	 */
	@RequestMapping(value = "/allApplys", method = RequestMethod.POST)
	@ResponseBody
	public Pagination findAllApplys(int type, String[] para,int pageSize,int pageNo) {
		
		if(para == null){
			String a[] = {"","","",""};
			para = a;
		}
System.out.println("___________---------");
		Pagination pagination = teacherService.queryAllApplys(type, para, pageSize,pageNo);
		return pagination;
	}
	
	
	/**
	 * 分页带参查询老师对应的学生外出申请记录信息
	 * 
	 * @param pib
	 * @return
	 */
	@RequestMapping(value = "/apply")
	@ResponseBody
	public Pagination findStuInfosOfApply(HttpSession session,
			ParentApplyFront paf) {
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		Pagination pagination = teacherService.queryApplysByTeacher(tTeacher,
				paf);
		// if (pagination == null) {
		// pagination = new Pagination(0, "", new ArrayList());
		// }
		return pagination;
	}

	@RequestMapping("/getCurTea")
	@ResponseBody
	public Object getCurTea(HttpSession session) {
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		DClass dClass = new DClass();
		dClass.setTeachername(tTeacher.getName());
		if (tTeacher.getTClass() != null) {
			dClass.setName(tTeacher.getTClass().getName());
		} else {
			dClass.setName("未知班级");
		}
		return dClass;
	}

	@RequestMapping("/getCurTeaStus")
	@ResponseBody
	public Object getCurTeaStus(HttpSession session,
			@RequestParam Integer pageSize, @RequestParam Integer pageNo) {
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		Pagination pagination = teacherService.getCurTeaStus(tTeacher, pageNo,
				pageSize);

		return pagination;
	}
	
	@RequestMapping("/getOneApply")
	@ResponseBody
	public Object getOneApply(@RequestParam Integer id){
		
		OutrequestInfo info = teacherService.getOneApply(id);
		
		return info;
	}
	
	
	@RequestMapping(value = "/replace", method = RequestMethod.POST)
	@ResponseBody
	public int replaceList(@RequestBody List<OutrequestInfo> infos,
			HttpSession session) {
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		int res = teacherService.saveReplaceList(infos, tTeacher);
		return res;
	}

	@RequestMapping(value = "/approve", method = RequestMethod.POST)
	@ResponseBody
	public int approveList(@RequestBody List<OutrequestInfo> infos) {
		int res = teacherService.updateApproveList(infos);
		return res;
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 用户退出
	 * 
	 * @param session
	 */
	@RequestMapping("/exit")
	@ResponseBody
	public void exit(HttpSession session) {
		session.removeAttribute("loginUser");
	}

	/**
	 * 生成前台登录页面验证码
	 * 
	 * @param parent
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/imageCode")
	public void getImageCode(HttpServletRequest request,
			HttpServletResponse response, ImageCode imageCode)
			throws IOException {
		String clientId = request.getRequestedSessionId();
		// 禁止图片缓存
		response.setHeader("Progma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 表明生成的响应是图片
		response.setContentType("image/jpeg");
		// 将图像输出到OutputStream流中
		OutputStream outputStream = response.getOutputStream();
		imageCode.setSessionKey("ImageCode" + clientId);
		ImageIO.write(imageCode.getImage(request), "jpeg", outputStream);
		// 关闭流
		outputStream.close();
	}

	/**
	 * 前台教师端端登录
	 * 
	 * @param parent
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	@ResponseBody
	public Object check(HttpSession session,
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "userName", required = true) String userName,
			@RequestParam(value = "password", required = true) String password) {
		String clientId = session.getId();
		String baseCode = (String) session.getAttribute("ImageCode" + clientId);
		if (baseCode == null || !baseCode.equalsIgnoreCase(code)) {// 忽略大小写
			return staticErrorCode.error_code_mismatch_verifyCode;
		}
		TTeacher tTeacher = teacherService.check(userName, password);
		if (tTeacher != null) {
			session.setAttribute("loginUser", tTeacher);
			return staticErrorCode.error_code_success;
		} else {
			return staticErrorCode.error_code_mismatch_user_or_password;
		}
	}

	/**
	 * 教师端微信登录
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/weChatLogin")
	@ResponseBody
	public Object weChatLogin(@RequestParam String name, @RequestParam String password,HttpSession session){
			String weixinId = (String) session.getAttribute("weixinId");
			TTeacher tTeacher =teacherService.modifyTeacher(name,password, weixinId);
			if (tTeacher != null) {
				session.setAttribute("loginUser", tTeacher);
				return staticErrorCode.error_code_success;
			} else {
				return staticErrorCode.error_code_mismatch_wxBind_fail;
			}
	}

	// public String weChatCheck(HttpServletRequest request) throws Exception{
	// HttpSession session = request.getSession();
	// String state =request.getParameter("state");
	// String forwardURL = "/front_end/weChat/login_weChat";
	// if(null!=request.getParameter("state")&&"parent".equals(request.getParameter("state")))
	// {//家长端 微信链接触发
	// String code = request.getParameter("code");
	// OAuth oa = getOAuth(null, code);
	// String weixinId = oa.getOpenid();
	// if(null!=weixinId&&!"".equals(weixinId))
	// {
	// session.setAttribute("weixinId", weixinId);
	// TTeacher tTeacher = teacherService.wxLogin(weixinId);
	// if(tTeacher!=null)
	// {
	// session.setAttribute("loginUser", tTeacher);
	// forwardURL =
	// "/front_end/weChat/patriarch/apply.detail_weReplace_teacher.html";
	// return forwardURL;
	// }
	// else
	// {
	// return forwardURL;
	// }
	// }
	// else
	// {
	// return forwardURL;
	// }
	// }
	// return forwardURL;
	// }
	/**
	 * 前台微信端用户绑定 2017年2月14日 09:55:51修改 修改原因:统一对接微信接口controller 修改人:张羽
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/weChatCheck")
	public String weChatCheck(HttpSession session) throws Exception {
		String forwardURL = "redirect:/front_end/weChat/u-teacher/login_weChat_teacher.html";
		String weixinId = (String) session.getAttribute("wexinId");
		if (null != weixinId && !"".equals(weixinId)) {
//			session.setAttribute("weixinId", weixinId);
			TTeacher tTeacher = teacherService.wxLogin(weixinId);
			if (tTeacher != null) {
				session.setAttribute("loginUser", tTeacher);
				forwardURL = "redirect:/front_end/weChat/u-teacher/record.weBack_teacher.html";
				return forwardURL;
			} else {
				return forwardURL;
			}
		} else {
			return null;
		}
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 日期处理 自动转换前台日期格式
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// 日期处理
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		df.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
		binder.registerCustomEditor(Timestamp.class,
				new PropertyEditorSupport() {
					@Override
					public void setAsText(String value) {
						setValue(new Timestamp(Long.valueOf(value)));
					}
				});
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 微信绑定 获取微信用户 openid 并保存到数据库
	 * 
	 * @param path
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public OAuth getOAuth(String path, String code) throws Exception {
		OAuth oa = null;
		System.out.println("获取网页授权凭据");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx546829eea71a10db&secret=601cbb8a2cef1cb23ca2b66614fd074b&code="
				+ code + "&grant_type=authorization_code";
		String json = HttpClientUtil.httpGetRequest(url);
		if (json != null && !"".equals(json)) {
			oa = (OAuth) JacksonUtil.json2object(json, OAuth.class);
		}
		return oa;
	}
	// ------------------------------------------------------------------------------------

}
